import { watch, ref, computed, nextTick, Ref, ComputedRef } from 'vue'
import { ElMessage } from 'element-plus'
import { global, loadCss, loadScript } from '@jsjn/utils'
import { forParent } from '@jsjn/micro-core-micro-main/sendData'

const printDocumentTitleId = 'print-document-title__wrapper'

export default () => {
    const currentTaskNodeInfo = global['__WORKFLOW_CURRENT_TASK_NODE__']
    const taskTitle = currentTaskNodeInfo
        ? `${currentTaskNodeInfo.processInstName}-${currentTaskNodeInfo.workItemName}`
        : ''
    const isLoadPrintSource = ref<boolean>(false)

    async function _print() {
        const printJS = await getPrintJs()
        const dom2Img = await getDom2Img()

        const $microShadowHtml: HTMLHtmlElement = window.document.querySelector('html')
        const $workflowMicroWrapper: HTMLHtmlElement = window.document.querySelector(
            '#micro-workflow-module-advance__wrapper'
        )

        // 添加标题
        _addDocumentTitle($workflowMicroWrapper)
        // 文档 rem 适配
        _addAttr($microShadowHtml, 'style', 'font-size: 100px;')
        // 文档展开（防止溢出隐藏，加载不到）
        _addAttr($workflowMicroWrapper, 'style', 'overflow: initial; height: fit-content;')

        // 获取 dom img
        const pageImgDataUrl = await dom2Img.toPng($workflowMicroWrapper).catch((err) => {
            _changePrintState(false)
            ElMessage.error('打印失败，请重试！')
            return null
        })
        if (!pageImgDataUrl) return false
        _removeDocumentTitle($workflowMicroWrapper)
        _removeAttr($microShadowHtml, 'style')
        _removeAttr($workflowMicroWrapper, 'style')

        // 打印 img
        printJS({
            printable: pageImgDataUrl,
            type: 'image',
            // documentTitle: taskTitle,
            style: `@media print { 
                        @page {
                            size: auto; 
                            margin: 0; 
                        } 
                        body {
                            margin: 0 5px;
                        }
                    }`
        })

        _changePrintState(false)
    }

    // 为打印的资源添加标题
    function _addDocumentTitle(parent: HTMLHtmlElement) {
        const $printTitle = document.createElement('h1')
        $printTitle.innerText = taskTitle
        $printTitle.id = printDocumentTitleId
        $printTitle.style.fontSize = '30px'
        $printTitle.style.textAlign = 'center'
        $printTitle.style.marginBottom = '20px'
        $printTitle.style.marginTop = '20px'
        parent.insertBefore($printTitle, parent.firstChild)
    }
    function _removeDocumentTitle(parent: HTMLHtmlElement) {
        const $printTitle = parent.querySelector(`#${printDocumentTitleId}`)
        parent.removeChild($printTitle)
    }

    function _changePrintState(flag: boolean) {
        isLoadPrintSource.value = flag
        forParent({ loadPrintSourceFlag: flag })
    }

    function printHandle() {
        _changePrintState(true)
        setTimeout(() => {
            _print()
        }, 50)
    }

    return {
        isLoadPrintSource,
        printHandle
    }
}

function _addAttr(dom: HTMLHtmlElement, attr: keyof HTMLHtmlElement, val: string) {
    dom.setAttribute(attr, val)
}

function _removeAttr(dom: HTMLHtmlElement, attr: keyof HTMLHtmlElement) {
    dom.removeAttribute(attr)
}

async function getPrintJs() {
    if (window['printJS']) return window['printJS']
    loadCss('/print-js/print.css')
    const printJS = await loadScript('/print-js/print.js', 'printJS')
    return printJS
}

async function getDom2Img() {
    if (window['domtoimage']) return window['domtoimage']
    const domtoimage = await loadScript('/dom-to-image/dom-to-image.min.js', 'domtoimage')
    return domtoimage
}
